﻿#include "overallsituation.h"

int SerialPort;
int row;//行
int column;//列
int NewSerialportNum;//现在选择的是几号重置口
int AppointFirstNum;//现在选择的是几号优先串口
int UploadNum=0;//上传数量

bool IsWarnInstance=false;//是否是警情模式
bool IsTerface=false;//是否进入接口映射
bool IsSwitch=false;//接口映射
bool IsDeleteFiles=false;//是否删除文件
bool IsC7Task=true;//任务是否完成;
bool IsUploadTask=true;//任务是否完成；
bool IsUploadTwoTask=true;//任务是否完成；
bool IsUDrive=false;//是否是盘符
//是否转盘完成
bool IsC6=true;//
bool IsT6=true;//
bool IsR1=true;//
bool Is3A=true;//
bool IsC7=true;//
bool IsUpload=true;//
bool IsPUpload=true;//
//QString Name="";
//QString Version="";
//QString Model="";
//QString Date="";
//QString Icon="";
//QString PrintLog="";
//QString Area="";//地区
//QString ServerAddress="";//服务IP
//QString ServerPor="";//服务端口
//QString BVersion="";//后台版本
//QString URL="";//后台地址
//QString Ttime="";//后台心跳时间
//QString NetworkName="";//网络名称
QString cloudIp="";//采集站IP
QString station_number="" ;//采集站编号
QString access_key="" ;//采集站秘钥
//QString UploadUrl="" ;//上传路径
//QString MountUrl="" ;//挂载根目录
//QString DeleteFiles="";//上传是否删除文件
//QString MUI="";
//QString PortNum="";
//QString MemoryLack="";
//QString CPULack="";
//QString Camera="";
//QString TheLocalKey="";
//QString TheLocalKeyPDW="";
//QString Sockettime="";
//QString Mode="";
//QString FingerPrint="";
//QString FaceRecognition="";
//QString MaxUploadRate="";//最大上传速率
//QString prior="";
//QString System="";//系统
QString FingerprintData="";//指纹数据
QString IP="";//IP地址
qint64 Lasttimes =0;//上一次重传时间
qint64 Noticetimes =0;//上一次重传时间
int NoticeFailNum =0;//后台失败次数

QString downloadSpeed;//下载
QString uploadSpeed;//上传
double TotalGB ;
double FreeGB ;
//int  UploadRate;//最大上传速率
QMutex myVecMutex;
QMutex DeviceserialMutex;
QMutex DriveLetterMutex;


double fileallsize[SYSTEMSUM];
int  IsBackdll[SYSTEMSUM];//dll调用是否成功 0进入转盘 1转盘成功 -1转盘失败 2磁盘模式 3正在传盘
bool IsPriorlize[SYSTEMSUM];//是否为优先口 true为优先口，false反正
bool IsInitalize[SYSTEMSUM];//是否初始化 true为已经初始化成功，false反正
bool IsALLlist[SYSTEMSUM];//是否重置路径 true为已经重置成功，false反正
bool IsExtract[SYSTEMSUM];//是否拔出 true为已经重置成功，false反正
bool IsinUpload[SYSTEMSUM];//是否上传 true为已经重置成功，false反正
double totalSize[SYSTEMSUM];
double  TemporarytotalSize[SYSTEMSUM];//设备数据大小
 qint64 UploadSchedule[SYSTEMSUM];
 qint64 LastTemporarytotalSize[SYSTEMSUM];//上一次设备数据大小
int IdentElectricity[SYSTEMSUM];
QString cSerial[SYSTEMSUM];         //执法记录仪产品序号
QString userNo[SYSTEMSUM];      //执法记录仪警员编号
QString userName[SYSTEMSUM]; //执法记录仪警员名称
QString unitNo[SYSTEMSUM];       //执法记录仪单位编号
QString unitName[SYSTEMSUM];  //执法记录仪单位名称
QString status[SYSTEMSUM];   //执法仪禁用状态
QString bindStatus[SYSTEMSUM];//执法仪配对状态；
QString watermark[SYSTEMSUM];//水印；
QString resolution[SYSTEMSUM];//分辨率；



QString IdentModel[SYSTEMSUM];//记录设备型号
QString IdentNumber[SYSTEMSUM];//记录设备标识号
QString IsUdisk[SYSTEMSUM];//转盘是否成功 有值则有，没有则无
QString Uploadtime[SYSTEMSUM];//开始上传时间
std::vector<Announcement> Notice;
std::vector<DeviceInforMation> myVec;//接入的设备信息
std::vector<DepartmentInfo>Filetype ;//文件类型
std::vector<DepartmentInfo>DepartmentName ;//部门名称
std::vector<WarnInfo>PoliceInfo ;//警情名称
std::list<BindingInfo>BindList;//绑定信息
std::list<Send> Send_List;                             // 任务队列
std::multimap<int,QString> AnalysisPath;//解析路径
std::multimap<int,QString> TemporaryPath;//临时路径
std::vector<UsbInfo> usbInfo;//接入的设备信息
std::list<RetranSmission>ARQList;//重传
DeviceInforMation deviceinfo;
UploadInfo Upload;
UploadInfo UploadTwo;
CallingDLL dll;
FileOperation config;
LinuxSystemMethod sys;

//加密 cbc pkcs5padding 本身实现  //pkcs7padding 跟 pkcs5padding是同样的
std::string des_cbc_pkcs5_encrypt(const std::string &clearText)
{
    static unsigned char cbc_iv[8] = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
    //初始化IV向量【我这边密码与IV相同】
    std::string strCipherText;
    DES_cblock keyEncrypt, ivec;

    memcpy(keyEncrypt, cbc_iv, sizeof(cbc_iv));

    DES_key_schedule keySchedule;  //密钥表
    DES_set_key_unchecked(&keyEncrypt, &keySchedule);   //设置密钥，且不检测密钥奇偶性

    memcpy(ivec, cbc_iv, sizeof(cbc_iv));

    // 循环加密，每8字节一次
    const_DES_cblock inputText;
    DES_cblock outputText;
    std::vector<unsigned char> vecCiphertext;
    unsigned char tmp[8];

    for (int i = 0; i < clearText.length() / 8; i++)
    {
        memcpy(inputText, clearText.c_str() + i * 8, 8);
        DES_ncbc_encrypt(inputText, outputText, 8, &keySchedule, &ivec, DES_ENCRYPT);  //加密
        memcpy(tmp, outputText, 8);

        for (int j = 0; j < 8; j++)
            vecCiphertext.push_back(tmp[j]);

        //重置ivec
        memcpy(ivec, outputText, 8);
    }

    if (clearText.length() % 8 != 0)
    {
        int tmp1 = clearText.length() / 8 * 8;
        int tmp2 = clearText.length() - tmp1;
        memset(inputText,(8-tmp2), 8);
        memcpy(inputText, clearText.c_str() + tmp1, tmp2);
    }
    else
    {
        memset(inputText,8, 8);
    }
    // 加密函数
    DES_ncbc_encrypt(inputText, outputText, 8, &keySchedule, &ivec, DES_ENCRYPT);  //加密

    memcpy(tmp, outputText, 8);

    for (int j = 0; j < 8; j++)
        vecCiphertext.push_back(tmp[j]);

    strCipherText.clear();
    strCipherText.assign(vecCiphertext.begin(), vecCiphertext.end());
    return strCipherText;
}

//解密 cbc pkcs5padding 本身实现  //zeropadding / pkcs7padding 跟 pkcs5padding是同样的
std::string des_cbc_pkcs5_decrypt(const std::string &cipherText)
{
    static unsigned char cbc_iv[8] = {'t', 'c', 'l', 'd', 'i', 'g', 'i', 't'};
    //初始化IV向量
    std::string clearText;
    DES_cblock keyEncrypt, ivec;

    memcpy(keyEncrypt, cbc_iv, sizeof(cbc_iv));

    DES_key_schedule keySchedule;  //密钥表
    DES_set_key_unchecked(&keyEncrypt, &keySchedule);   //设置密钥，且不检测密钥奇偶性

    memcpy(ivec, cbc_iv, sizeof(cbc_iv));

    // 循环解密，每8字节一次
    const_DES_cblock inputText;
    DES_cblock outputText;
    std::vector<unsigned char> vecCleartext;
    unsigned char tmp[8];

    for (int i = 0; i < cipherText.length() / 8; i++)
    {
        memcpy(inputText, cipherText.c_str() + i * 8, 8);
        DES_ncbc_encrypt(inputText, outputText, 8, &keySchedule, &ivec, DES_DECRYPT);  //解密
        memcpy(tmp, outputText, 8);

        for (int j = 0; j < 8; j++)
            vecCleartext.push_back(tmp[j]);

        //重置ivec
        //memcpy(ivec, outputText, 8);  //解密过程不须要用前一块的结果做为下一块的IV
    }

    if (clearText.length() % 8 != 0)
    {
        int tmp1 = clearText.length() / 8 * 8;
        int tmp2 = clearText.length() - tmp1;
        memset(inputText,0, tmp2);
        memcpy(inputText, cipherText.c_str() + tmp1, tmp2);
        DES_ncbc_encrypt(inputText, outputText, tmp2, &keySchedule, &ivec, DES_DECRYPT);  //解密
        memcpy(tmp, outputText, tmp2);
        for (int j = 0; j < 8; j++)
            vecCleartext.push_back(tmp[j]);
    }
    clearText.clear();
    clearText.assign(vecCleartext.begin(), vecCleartext.end());
    return clearText;
}

// 加密后密文转hex
std::string StringToHex(const std::string& data)
{
    const std::string hex = "0123456789ABCDEF";
    std::stringstream ss;

    for (std::string::size_type i = 0; i < data.size(); ++i)
        ss << hex[(unsigned char)data[i] >> 4] << hex[(unsigned char)data[i] & 0xf];

    return ss.str();
}



inline void DeviceInfo()
{
    deviceinfo.Indet=-1;
    deviceinfo.serialportnum=-1;//几号串口
    deviceinfo.serialport="";
    deviceinfo.vid= "";//vid
    deviceinfo.pid= "";//pid
    deviceinfo.serialnumber= "";//设备序列号
    deviceinfo.manufacturer= "";//设备制造商 3
    deviceinfo.model= "";//设备型号 4
    deviceinfo.route= "";//位置路径
    deviceinfo.Device= "";// 是否为优先
    deviceinfo.Identnumber= "";// 是否为优先
}
void InterfaceMapInfo()
{
    QString value="";
    QString Drive="";
    getUsbInfo();
    //获取初始化
    for (int r = 1; r <= row; r++) {
        for (int col = 1; col <= column; col++) {
            int number = (r - 1) * 5 + col;  // 计算当前格子的数字
            IsInitalize[number-1]=true;//设置为已经初始化
        }
    }
    //对所有串口检验
    for(int q=1;q<=(SYSTEMROW*SYSTEMLIST);q++)
    {

        DeviceInfo();
        deviceinfo.serialportnum=q;
        /*例2、获取界面中的名字叫label的QLabel*/
        if(config.ReadRouteInfo("config_route.ini",QString("Initalize_%1").arg(q),value))//已经获取的路径文件
        {
            IsALLlist[q]=true;//是否重置路径
            //初始化容器

            QStringList list = value.split(";");

            if (list.length() > 1) {
                foreach (QString item, list) {
                    if(item!="")
                    {
                        AnalysisPath.insert(std::pair<int, QString>(q, item));

                        // deviceinfo.serialport = item;//路径拷贝
                    }
                }
            } else {
                qDebug() << "字符串中没有分号：" << value;
            }
            //上一次转盘成功未拔出来的设备
            if(config.ReadRouteInfo("config_record.ini",QString("label_%1").arg(q),Drive))//已经获取的路径文件
            {
                if(Drive!="")
                {
                    QString beforeComma=Drive.section(';',0,0);
                    QString serialnumber=Drive.section(';',1,1);
                    QString afterComma=Drive.section(';',2,2);
                    QString Bus=Drive.section(';',3,3);


                    qDebug() << serialnumber<<"serialnumber";
                    qDebug() << Bus<<"Bus";
                    // 输出截取的子串
                    qDebug() << beforeComma<<"beforeComma";
                    qDebug() << afterComma<<"afterComma";


                    auto it = std::find_if(usbInfo.begin(), usbInfo.end(), [&](const UsbInfo Info) {
                        qDebug() <<Info.Bus<<Bus;
                        return (Info.Bus==Bus);
                    });

                    // If the target element is found, erase itvid from the vector
                    if (it != usbInfo.end()) {
                        if (sys.getPathSpace(beforeComma)&&beforeComma!="")
                        {
                            QString Drice="";
                            if(config.ReadRouteInfo(QString("%1/ZFYConfig.ini").arg(beforeComma),"PID",Drice))
                            {
                                config.WriteInfo(QString("Drice=%1").arg(Drice));
                                if(Drice==afterComma)//防止不是上一个磁盘
                                {
                                    deviceinfo.serialnumber=serialnumber;
                                    deviceinfo.Device=beforeComma;
                                    deviceinfo.Bus=Bus;
                                    IsUdisk[q]=beforeComma;
                                    IdentNumber[q]=afterComma;
                                }
                                else
                                {
                                    //该盘符已经拔出
                                    config.UpdateRouteValueInfo("config_record.ini",QString("label_%1").arg(q),"");
                                }
                            }
                        }
                        else
                        {
                            //该盘符已经拔出
                            config.UpdateRouteValueInfo("config_record.ini",QString("label_%1").arg(q),"");
                        }
                    }
                    else
                    {
                        //该盘符已经拔出
                        config.UpdateRouteValueInfo("config_record.ini",QString("label_%1").arg(q),"");
                    }

                }

            }
        }
        myVec.push_back(deviceinfo);
    }

}
QString generateRandomString()
{
    qDebug()<<"随机生成";
    const QString charset = "abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    QString randomString;

    for (int i = 0; i < 7; ++i) {
        int index = QRandomGenerator::global()->bounded(charset.length());
        randomString.append(charset.at(index));
    }
    return randomString;
}
void GetSerialNumber(int serialportnum,QString Device,QString serialnumber)
{
    //QApplication::processEvents();
    //获取该磁盘的序列号
    QString value="";
    config.ReadRouteInfo(QString("%1/ZFYConfig.ini").arg(Device),"PID",value);
    qDebug()<<value;
    //    if(IdentNumber[serialportnum]!=""&&IdentNumber[serialportnum]!=value)//dll有序列号但是和ZFYConfig不一样。用dll的
    //    {
    //        config.UpdateRouteValueInfo(QString("%1/ZFYConfig.ini").arg(Device),"PID",IdentNumber[serialportnum]);
    //        qDebug()<<"以获取的dll的为准";
    //    }

    if(value!="")//ZFYConfig有。用ZFYConfig
    {
        IdentNumber[serialportnum]=value;
    }
    else if(IdentNumber[serialportnum]==""&&value=="")//dll没有序列号，ZFYConfig也没有。用驱动的实际路径
    {
        //        if(serialnumber=="1234567")
        //        {
        //            qDebug()<<"序列号为1234567";
        //            serialnumber=generateRandomString();
        //        }
        config.UpdateRouteValueInfo(QString("%1/ZFYConfig.ini").arg(Device),"PID",serialnumber);
        IdentNumber[serialportnum]=serialnumber;
    }
    //    else
    //    {
    //        serialnumber=generateRandomString();
    //        config.UpdateRouteValueInfo(QString("%1/ZFYConfig.ini").arg(Device),"PID",serialnumber);
    //        IdentNumber[serialportnum]=serialnumber;
    //    }
}
int GetMyVec(QString Route,QString Serialnumber)
{
    qDebug() << "GetMyVec";
    int index=0;
    QString serialnumber="";
    //int Num=0;
    myVecMutex.lock();
    if(Route!="")
    {

        auto it = std::find_if(myVec.begin(), myVec.end(), [&](const DeviceInforMation deviceInfo) {
            return (deviceInfo.route==Route);
        });

        // If the target element is found, erase itvid from the vector
        if (it!= myVec.end()) {
            config.WriteInfo(QString("GetMyVec,it->serialportnum=%1").arg(it->serialportnum));
            index=it->serialportnum;
        }
    }
    else if(Serialnumber!="")
    {
        auto it = std::find_if(myVec.begin(), myVec.end(), [&](const DeviceInforMation deviceInfo) {
            return (deviceInfo.serialnumber==Serialnumber);
        });

        // If the target element is found, erase itvid from the vector
        if (it != myVec.end()) {
            config.WriteInfo(QString("GetMyVec,it->serialportnum=%1").arg(it->serialportnum));
            index=it->serialportnum;
        }
    }
    myVecMutex .unlock();
    return index;
}
bool GetDeviceName(QString vid ,QString pid)
{
    if(vid=="0E8D"&&pid=="201C")//S2
    {
        qDebug()<<"GetDeviceName s2";
        config.WriteInfo("转盘开启");
        return true;

        //        QString processName = QString("adb -s %1 shell am broadcast -a \"tcl-mass-storage\"").arg("TCLS2A12340007");
        //        QProcess process;
        //        process.start(processName);
        //        process.waitForFinished(-1); // 等待进程完成
        //        if (process.exitCode() == 0) {
        //            QString output = process.readAllStandardOutput();
        //            qDebug() << "命令输出： " << output;
        //            qDebug() <<QString("ADB命令发送成功：%1").arg(output);

        //        }
    }
    if(vid=="1BBB"&&pid=="AF2E")
    {
        qDebug()<<"GetDeviceName c7";
        config.WriteInfo("转盘开启");
        return true;

    }
    else if((vid=="0E8D"&&pid=="201C")||(vid=="0e8d"&&pid=="201c"))
    {
        qDebug()<<"GetDeviceName c8||s1";
        config.WriteInfo("转盘开启");
        return true;

    }
    else if(vid=="18D1"&&pid=="4EE7")
    {
        qDebug()<<"GetDeviceName c9";
        config.WriteInfo("转盘开启");
        return true;

    }
    else if(vid=="1782"&&pid=="4012")
    {
        qDebug()<<"GetDeviceName c6";
        config.WriteInfo("转盘开启");
        return true;

    }
    else if(vid=="4255"&&pid=="0001")
    {
        qDebug()<<"GetDeviceName T6";
        config.WriteInfo("转盘开启");
        return true;

        // threadPool_C8->PushTask(threadinfo);
    }
    else if(vid=="4255"&&pid=="1000")
    {
        qDebug()<<"GetDeviceName T6";
        config.WriteInfo("转盘开启");
        return true;

        // threadPool_C8->PushTask(threadinfo);
    }
    return false;
}
int GetRoute(QString route)
{
    for (int i = 0; i < myVec.size(); ++i) {
        if(myVec[i].route!="")
        {
            QStringList routelist = myVec[i].route.split(";");

            if (routelist.length() > 1) {
                foreach (QString item, routelist) {
                    if(route==item)
                    {
                        return i;
                    }
                }
            }
        }
    }
    return -1;
}

void ListeningDisks(DeviceInforMation UsbInfo)
{
    config.WriteInfo(QString("检测到U盘或光盘:"));
    if(UsbInfo.serialport!="")
    {
        int Index=-1;

        std::multimap<int, QString>::iterator it = AnalysisPath.begin();
        while (it!=AnalysisPath.end())
        {

            if(it->second==UsbInfo.serialport&&UsbInfo.serialport!="")
            {
                Index=it->first;
            }
            ++it;
        }

        if(Index>0)
        {
            if(IsUdisk[Index]=="")
            {
                myVec[Index-1].serialport=UsbInfo.serialport;
                if(IdentNumber[Index]!="")//判断转盘是否放回标识号
                {
                    config.WriteInfo(QString("DLL放回序列号%1").arg(IdentNumber[Index]));
                    myVec[Index-1].Identnumber=IdentNumber[Index];//这里改

                }
                config.WriteInfo(QString("UsbInfo.Device=%1").arg(UsbInfo.Device));
                // 创建QFileInfo对象
                QFileInfo fileInfo(QString("%1/ZFYConfig.ini").arg(UsbInfo.Device));

                // 检查文件是否存在
                if (fileInfo.exists()) {
                    config.WriteInfo( "ZFYConfig文件存在") ;
                    GetSerialNumber(Index,UsbInfo.Device,myVec[Index-1].serialnumber.right(7));
                } else {
                    if(IdentNumber[Index]=="")
                        IdentNumber[Index]=myVec[Index-1].serialnumber.right(7);
                    config.WriteZFYConfig(UsbInfo.Device,IdentNumber[Index],myVec[Index-1].manufacturer,myVec[Index-1].model);
                }
                QString Dirve=QString("%1;%2;%3;%4").arg(UsbInfo.Device).arg(myVec[Index-1].serialnumber).arg(IdentNumber[Index]).arg(myVec[Index-1].Bus);
                if(config.UpdateRouteValueInfo("config_record.ini",QString("label_%1").arg(Index),Dirve))
                {

                    myVec[Index-1].Device=UsbInfo.Device;//这里改

                    IsUdisk[Index]=UsbInfo.Device;
                    IsExtract[Index]=false;
                    if(AppointFirstNum==Index)//优先口
                    {
                        emit GlobalSignals::instance().ThreadPriorUpload(Index+100,"","");
                    }
                    else
                    {
                        emit GlobalSignals::instance().ThreadUpload(Index+100,"","");
                    }

                    emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,Index+100,"",QString("%1;%2;%3").arg(UsbInfo.Device).arg(IdentNumber[Index]).arg(IdentElectricity[Index]),DISKMODE,-1);
                }
            }
            else
            {
                config.WriteInfo(QString("磁盘存在").arg(Index));
            }
        }
        else
        {
            config.WriteInfo(QString("该磁盘没有做过接口映射%2").arg(UsbInfo.Device));
        }

    }
    else
    {
        config.WriteInfo(QString("该磁盘没有路径"));
    }


    return;
}
void ListeningUnplug(QString Path)
{

    //int Num=0;
    int index=-1;

    std::multimap<int, QString>::iterator it = AnalysisPath.begin();
    while (it!=AnalysisPath.end())
    {

        config.WriteInfo(QString("监听到磁盘路径%1，存在的磁盘路径=%2").arg(Path).arg(it->second));
        if(it->second==Path&&Path!="")
        {
            index=it->first;
        }
        it++;
    }
    if(index>0&&myVec[index-1].serialport==Path)
    {
        config.WriteInfo(QString("磁盘拔出%1").arg(index));
        //        if (!IsExtract[index]){
        emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,myVec[index-1].serialportnum+100,""," ",IDLE,-1);

        myVec[index-1].route="";
        myVec[index-1].pid="";
        myVec[index-1].vid="";
        myVec[index-1].serialnumber="";
        myVec[index-1].manufacturer="";
        myVec[index-1].model="";
        myVec[index-1].Device="";
        myVec[index-1].Identnumber="";
        IsUdisk[index]="";
        if(config.UpdateRouteValueInfo("config_record.ini",QString("label_%1").arg(index),""))
        {

            //写入成功
        }

        IsBackdll[index]=-1;
        //IsExtract[index]=true;
        IdentNumber[index]="";

        //}


    }

    return;
}
void ListeningAccess(DeviceInforMation UsbInfo)
{

    //DeviceInforMation Dinfo;
    if(IsTerface==false)//没有重置进入识别
    {/*

        for(int i=0;i<DePositPairDinfo.size();i++)
        {*/
        int index=-1;

        std::multimap<int, QString>::iterator it = AnalysisPath.begin();
        while (it!=AnalysisPath.end())
        {

            if(it->second==UsbInfo.serialport&&UsbInfo.serialport!="")
            {
                index=it->first;

                //        auto it = std::find_if(myVec.begin(), myVec.end(), [&](const DeviceInforMation deviceInfo) {
                //            config.WriteInfo(deviceInfo.serialport);
                //            return (deviceInfo.serialport==UsbInfo.serialport);
                //        });

                //        // If the target element is found, erase itvid from the vector
                //        if (it != myVec.end()) {

                //   index=it->serialportnum;
                if(IsInitalize[index])//判读是否初始化
                {
                    config.WriteInfo(QString("GetMyVec,it->serialportnum=%1").arg(index));

                    IsExtract[index]=false;//一个设备拔出可能有多个驱动，防止多拔出
                }
                else
                {
                    config.WriteInfo(QString("未初始化:"));
                }

                if(index>0)
                {

                    config.WriteInfo(QString("设备接入的标识号:%1").arg(IdentNumber[index]));
                    config.WriteInfo(QString("设备接入的dll调用是否成功:%1").arg(IsBackdll[index]));
                    if (IsUdisk[index]==""&&IsBackdll[index]!=0&&IsBackdll[index]!=3)//已经是磁盘了就不做转盘
                    {
                        myVec[index-1].vid=UsbInfo.vid;
                        myVec[index-1].pid=UsbInfo.pid;
                        myVec[index-1].serialnumber=UsbInfo.serialnumber;
                        myVec[index-1].manufacturer=UsbInfo.manufacturer;
                        myVec[index-1].model=UsbInfo.model;
                        myVec[index-1].route=UsbInfo.route;
                        myVec[index-1].Device=UsbInfo.Device;
                        myVec[index-1].Identnumber=UsbInfo.Identnumber;
                        myVec[index-1].Bus=UsbInfo.Bus;
                        myVec[index-1].serialport=UsbInfo.serialport;
                        IdentModel[index]=myVec[index-1].model;
                        if(GetDeviceName(myVec[index-1].vid, myVec[index-1].pid))//转盘
                        {

                            emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,index+100,"","",TURNINGTHEDIAL,-1);

                            config.WriteInfo(QString("ThreadJoin"));
                            IsBackdll[index]=0;
                            config.WriteInfo(QString("index=%1").arg(index));
                            emit GlobalSignals::instance().ThreadJoin(index,myVec[index-1].vid, myVec[index-1].pid, myVec[index-1].serialnumber);
                        }
                        else
                        {

                            config.WriteInfo(QString("没有做适配:"));
                        }

                    }
                    else if(IsBackdll[index]==0)
                    {
                        config.WriteInfo(QString("进入转盘:"));

                    }
                }

            }
            it++;

        }
        //        else
        //        {

        //            config.WriteInfo(QString("该串口位置不可用！:"));
        //        }
        // }
    }
    else if((IsTerface==true&&!IsALLlist[NewSerialportNum])||(IsSwitch==true&&IsTerface==true))//存在不可用的串口并按顺序重置
    {
        config.WriteInfo(QString("接口映射重置！:%1").arg(NewSerialportNum));
        int whether=true;
        if(UsbInfo.serialport!="")
        {

            std::multimap<int, QString>::iterator it = TemporaryPath.begin();
            while (it!=TemporaryPath.end())
            {
                if((*it).second==UsbInfo.serialport)
                {
                    config.WriteInfo(QString("已经存在该路径！:"));
                    whether=false;
                }
                it++;
            }
            if(whether)
            {
                TemporaryPath.insert(std::pair<int, QString>(NewSerialportNum, UsbInfo.serialport));
                NextInit();

            }
        }


        return;
    }
    else
    {
        config.WriteInfo(QString("程序错误"));
    }
    return;
}
void NextInit()
{
    IsALLlist[NewSerialportNum]=true;
    emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,NewSerialportNum,"","",INITIALIZED,-1);
    for(int j=NewSerialportNum+1;j<=SYSTEMROW*SYSTEMLIST;++j)
    {
        config.WriteInfo(QString("接口映射重置J=:%1").arg(j));
        config.WriteInfo(QString("接口映射重置:%1").arg(IsInitalize[j]));
        config.WriteInfo(QString("接口映射重置:%1").arg(IsALLlist[j]));
        if(IsInitalize[j]&&!IsALLlist[j])//此串口还没存在，并且获取的最新位置信息不为空
        {
            NewSerialportNum =j;
            emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,NewSerialportNum,"","",INITIALIZING,-1);
            break;
        }

    }
    config.WriteInfo(QString("接口映射重置:"));
}
//拍照
void TurnUpCamera()
{
    QCamera camera(QCameraInfo::defaultCamera());
    QCameraImageCapture imageCapture(&camera);
    QMediaRecorder mediaRecorder(&camera);
    QVideoWidget videoWidget;

    camera.setCaptureMode(QCamera::CaptureStillImage);
    camera.start();

    imageCapture.setCaptureDestination(QCameraImageCapture::CaptureToFile);

    QObject::connect(&imageCapture, &QCameraImageCapture::imageCaptured, [&imageCapture](int requestId, const QImage& img) {
        Q_UNUSED(requestId);
        // 处理拍照后的图像，例如显示在界面上
        // 你可以在这里添加你的处理逻辑
        QMessageBox::information(nullptr, QStringLiteral("拍照完成"), QStringLiteral("图片已保存"));
    });

    mediaRecorder.setOutputLocation(QUrl::fromLocalFile("output.mp4"));

    QPushButton photoButton(QStringLiteral("拍照"));
    QObject::connect(&photoButton, &QPushButton::clicked, [&imageCapture]() {
        QString fileName = QFileDialog::getSaveFileName(nullptr, QStringLiteral("保存图片"),
                                                        QDir::homePath(),
                                                        QStringLiteral("JPEG (*.jpg);;PNG (*.png)"));

        if (!fileName.isEmpty())
            imageCapture.capture(fileName);
    });

    QPushButton recordButton(QStringLiteral("录像"));
    QObject::connect(&recordButton, &QPushButton::clicked, [&mediaRecorder]() {
        if (mediaRecorder.state() == QMediaRecorder::StoppedState) {
            mediaRecorder.record();
        } else {
            mediaRecorder.stop();
        }
    });

    QVBoxLayout layout;
    layout.addWidget(&videoWidget);
    layout.addWidget(&photoButton);
    layout.addWidget(&recordButton);

    videoWidget.show();

}



void xorEncryptDecrypt(QByteArray& data, const QString& key) {
    // Convert the key to a QByteArray
    QByteArray keyData = key.toUtf8();
    // Perform the XOR operation with the key bytes
    data[0] = data[0] - keyData.at(0);
    data[1] = data[1] - keyData.at(1);
    data[2] = data[2] - keyData.at(2);
    data[3] = data[3] - keyData.at(3);
    data[4] = data[4] - keyData.at(4);
    data[5] = data[5] - keyData.at(5);
}
void xorEncryptDecrypt2(QByteArray& data, const QString& key) {
    // Convert the key to a QByteArray
    QByteArray keyData = key.toUtf8();

    // Perform the XOR operation with the key bytes
    data[0] = data[0] + keyData.at(0);
    data[1] = data[1] + keyData.at(1);
    data[2] = data[2] + keyData.at(2);
    data[3] = data[3] + keyData.at(3);
    data[4] = data[4] + keyData.at(4);
    data[5] = data[5] + keyData.at(5);
}
bool encryptFile(const QString& filePath, const QString& password) {
    QFile inputFile(filePath);
    if (!inputFile.open(QIODevice::ReadWrite)) {
        qDebug() << "Failed to open the file for encryption!";
        return false;
    }

    QByteArray fileData = inputFile.readAll();
    xorEncryptDecrypt(fileData, password);

    // Move to the beginning of the file to overwrite its content with the encrypted data
    inputFile.seek(0);
    inputFile.write(fileData);
    inputFile.close();

    qDebug() << "File encrypted successfully!";
    return true;
}

bool decryptFile(const QString& filePath, const QString& password) {
    QFile inputFile(filePath);
    if (!inputFile.open(QIODevice::ReadWrite)) {
        qDebug() << "Failed to open the file for decryption!";
        return false;
    }

    QByteArray fileData = inputFile.readAll();
    xorEncryptDecrypt2(fileData, password);

    // Move to the beginning of the file to overwrite its content with the decrypted data
    inputFile.seek(0);
    inputFile.write(fileData);
    inputFile.close();

    qDebug() << "File decrypted successfully!";
    return true;
}
void getUsbInfo()
{
    usbInfo.clear();
    // 创建一个QProcess对象
    QProcess process;

    // 设置要执行的命令
    process.start("lsusb");

    // 等待进程完成
    process.waitForFinished();

    // 读取命令输出
    QByteArray output = process.readAllStandardOutput();


    // 将输出转换为字符串并按行分割
    QList<QByteArray> lines = output.split('\n');

    // 定义正则表达式用于匹配输出行
    QRegularExpression regex("Bus (\\d+) Device (\\d+): ID (\\S+) (.+)");

    // 解析每行输出
    foreach (const QByteArray &line, lines) {
        // 进行正则表达式匹配
        QRegularExpressionMatch match = regex.match(line);

        // 如果匹配成功，提取Bus值、Device值、ID值和设备名称
        if (match.hasMatch()) {
            int bus = match.captured(1).toInt();
            int device = match.captured(2).toInt();
            QString id = match.captured(3);
            QString deviceName = match.captured(4);


            // 拆分ID值
            QStringList idParts = id.split(':');
            if (idParts.size() == 2) {
                QString vendorId = idParts[0];
                QString productId = idParts[1];

                UsbInfo Info;
                Info.Bus=QString("%1-%2").arg(bus).arg(device);
                Info.vid=vendorId;
                Info.pid=productId;
                Info.deviceName=deviceName;
                usbInfo.push_back(Info);


                // 输出提取的值
                qDebug() << "serialport:" << Info.Bus << "ID:" << vendorId<<"pid"<<productId<<"deviceName"<<deviceName;

            }
        }
    }


}



//void xorEncryptDecrypt(vector<char>& data, const string& key) {
//    for (size_t i = 0; i < data.size(); ++i) {
//        // Perform the XOR operation with the key bytes
//        data[i] = data[i] ^ key[i % key.size()];
//    }
//}

//void encryptFile(const string& filePath, const string& password) {
//    ifstream inputFile(filePath, ios::binary);
//    if (!inputFile) {
//        cout << "Failed to open the file for encryption!" << endl;
//        return;
//    }

//    vector<char> fileData((istreambuf_iterator<char>(inputFile)), (istreambuf_iterator<char>()));
//    xorEncryptDecrypt(fileData, password);

//    inputFile.close();

//    ofstream outputFile(filePath, ios::binary);
//    if (!outputFile) {
//        cout << "Failed to write encrypted data to file!" << endl;
//        return;
//    }

//    outputFile.write(fileData.data(), fileData.size());
//    outputFile.close();

//    cout << "File encrypted successfully!" << endl;
//}

//void decryptFile(const string& filePath, const string& password) {
//    ifstream inputFile(filePath, ios::binary);
//    if (!inputFile) {
//        cout << "Failed to open the file for decryption!" << endl;
//        return;
//    }

//    vector<char> encryptedData((istreambuf_iterator<char>(inputFile)), (istreambuf_iterator<char>()));
//    xorEncryptDecrypt(encryptedData, password);

//    inputFile.close();

//    ofstream outputFile(filePath, ios::binary);
//    if (!outputFile) {
//        cout << "Failed to write decrypted data to file!" << endl;
//        return;
//    }

//    outputFile.write(encryptedData.data(), encryptedData.size());
//    outputFile.close();

//    cout << "File decrypted successfully!" << endl;
//}

GlobalSignals::GlobalSignals() {
    //config_t=new ReadConfig;
}


